#!/bin/bash

# RK3588智能表情交互系统 - Qt标准构建脚本
# 使用Qt官方推荐的构建方式

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目配置
PROJECT_NAME="qt_cpp"
BUILD_DIR="build"
PRO_FILE="qt_cpp.pro"

# 打印函数
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查Qt环境
check_qt_environment() {
    print_info "检查Qt开发环境..."
    
    # 检查qmake
    if ! command -v qmake &> /dev/null; then
        print_error "qmake未找到，请安装Qt5开发环境"
        print_info "Ubuntu/Debian: sudo apt install qt5-qmake qtbase5-dev"
        exit 1
    fi
    
    # 检查make
    if ! command -v make &> /dev/null; then
        print_error "make未找到，请安装构建工具"
        print_info "Ubuntu/Debian: sudo apt install build-essential"
        exit 1
    fi
    
    # 显示Qt版本信息
    print_info "Qt版本信息:"
    qmake --version
    
    print_success "Qt环境检查通过"
}

# 检查项目依赖
check_dependencies() {
    print_info "检查项目依赖..."
    
    # 检查.pro文件
    if [ ! -f "$PRO_FILE" ]; then
        print_error "未找到项目文件 $PRO_FILE"
        exit 1
    fi
    
    # 检查源代码目录
    if [ ! -d "src" ]; then
        print_error "未找到源代码目录 src/"
        exit 1
    fi
    
    # 检查科大讯飞SDK
    if [ -f "../kedaxunf/libs/libaikit.so" ]; then
        print_success "找到科大讯飞SDK"
    else
        print_warning "未找到科大讯飞SDK，将使用模拟实现"
    fi
    
    print_success "项目依赖检查完成"
}

# 清理构建目录
clean_build() {
    print_info "清理构建目录..."
    
    if [ -d "$BUILD_DIR" ]; then
        cd $BUILD_DIR
        if [ -f "Makefile" ]; then
            make clean &> /dev/null || true
        fi
        cd ..
        rm -rf $BUILD_DIR
    fi
    
    mkdir -p $BUILD_DIR
    print_success "构建目录已清理"
}

# 生成Makefile
generate_makefile() {
    print_info "使用qmake生成Makefile..."
    
    cd $BUILD_DIR
    
    # 使用qmake生成Makefile
    if qmake ../$PRO_FILE; then
        print_success "Makefile生成成功"
    else
        print_error "qmake失败"
        exit 1
    fi
    
    cd ..
}

# 编译项目
compile_project() {
    print_info "编译Qt项目..."
    
    cd $BUILD_DIR
    
    # 获取CPU核心数用于并行编译
    JOBS=$(nproc)
    print_info "使用 $JOBS 个并行任务编译"
    
    # 编译项目
    if make -j$JOBS; then
        print_success "项目编译成功"
    else
        print_error "项目编译失败"
        cd ..
        exit 1
    fi
    
    cd ..
}

# 检查编译结果
check_result() {
    print_info "检查编译结果..."
    
    EXECUTABLE="$BUILD_DIR/$PROJECT_NAME"
    
    if [ -f "$EXECUTABLE" ]; then
        print_success "可执行文件生成成功: $EXECUTABLE"
        
        # 显示文件信息
        print_info "文件信息:"
        ls -lh "$EXECUTABLE"
        
        # 检查动态库依赖
        print_info "动态库依赖:"
        ldd "$EXECUTABLE" | head -10
        
        # 将可执行文件复制到项目根目录，方便直接运行/部署
        cp -f "$EXECUTABLE" "./$PROJECT_NAME"
        print_success "已将可执行文件复制到项目根目录: ./$PROJECT_NAME"
        
        return 0
    else
        print_error "可执行文件未生成"
        return 1
    fi
}

# 运行测试
run_test() {
    print_info "运行基本测试..."
    
    EXECUTABLE="$BUILD_DIR/$PROJECT_NAME"
    
    if [ -f "$EXECUTABLE" ]; then
        print_info "测试程序启动..."
        
        # 设置显示变量（如果在SSH中运行）
        if [ -z "$DISPLAY" ]; then
            export QT_QPA_PLATFORM=offscreen
            print_warning "无显示环境，使用离屏模式"
        fi
        
        # 运行程序（超时5秒）
        timeout 5s "$EXECUTABLE" &> /dev/null && print_success "程序启动测试通过" || print_warning "程序启动测试超时（这在无显示环境下是正常的）"
    fi
}

# 显示构建摘要
show_summary() {
    print_info "构建摘要:"
    echo "=========================================="
    echo "项目名称: $PROJECT_NAME"
    echo "构建工具: qmake + make"
    echo "构建目录: $BUILD_DIR"
    echo "可执行文件: $BUILD_DIR/$PROJECT_NAME"
    echo "根目录可执行文件: ./$PROJECT_NAME"
    echo "=========================================="
    
    print_info "项目结构:"
    if command -v tree &> /dev/null; then
        tree -L 2 -I 'build|*.o|moc_*|ui_*'
    else
        find . -type d -name build -prune -o -type d -print | sort
    fi
    
    print_success "Qt项目构建完成！"
    print_info "运行程序: cd $BUILD_DIR && ./$PROJECT_NAME"
}

# 主函数
main() {
    print_info "开始构建Qt项目 $PROJECT_NAME..."
    print_info "时间: $(date)"
    echo "=========================================="
    
    # 检查参数
    case "${1:-}" in
        "clean")
            clean_build
            print_success "清理完成"
            exit 0
            ;;
        "check")
            check_qt_environment
            check_dependencies
            print_success "环境检查完成"
            exit 0
            ;;
        "help"|"-h"|"--help")
            echo "用法: $0 [选项]"
            echo "选项:"
            echo "  clean    清理构建目录"
            echo "  check    检查环境和依赖"
            echo "  help     显示此帮助信息"
            echo "  (无参数) 完整构建项目"
            exit 0
            ;;
    esac
    
    # 执行构建步骤
    check_qt_environment
    check_dependencies
    clean_build
    generate_makefile
    compile_project
    
    if check_result; then
        run_test
        show_summary
    else
        print_error "构建失败"
        exit 1
    fi
}

# 运行主函数
main "$@" 